import appRouter from '@/routes/application';
import socketConnect from '@/socket';
import cors from 'cors';
import express from 'express';
import http from 'http';
import mongoose from 'mongoose';
import { Server } from 'socket.io';

import config from './config';
import pagesRouter from './routes/pages';
import repoRouter from './routes/repo';
import utilsRouter from './routes/utils';

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: config.cors,
});

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/repoStatic', express.static(config.repoPath));

// 数据库连接
mongoose
  .connect(config.database.url)
  .then(() => {
    console.log('MongoDB connected successfully');
  })
  .catch(err => {
    console.error('MongoDB connection error:', err);
  });

// WebSocket 连接处理
io.on('connection', socket => socketConnect(io, socket));

app.get('/', (_req, res) => {
  res.json({ message: 'Welcome to IM Server API' });
});

app.use('/api/repo', repoRouter);
app.use('/api/utils', utilsRouter);
app.use('/api/application', appRouter);
app.use('/api/pure', pagesRouter);

// 启动服务器
server.listen(config.server.port, () => {
  console.log(`Server is running on port ${config.server.port}`);
});
